<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Model\Cart;
use App\Model\Commodity_info;
use App\Model\Order;
use App\Model\Parent_order;
use App\Model\Trading_stream;
use App\Model\User;
use App\Model\User_address;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;

/**
 * Class OrderController
 * @package App\Http\Controllers\Api
 * @User wuqin
 * @Date 2018/4/11 0011
 * @Time 13:28
 */
class OrderController extends Controller
{
    /**
     * @var Order
     */
    private $order;
    /**
     * @var Parent_order
     */
    private $parent_order;
    /**
     * @var User
     */
    private $user;
    /**
     * @var Cart
     */
    private $cart;
    /**
     * @var Trading_stream
     */
    private $trading_stream;
    /**
     * @var Commodity_info
     */
    private $commodity_info;
    /**
     * @var User_address
     */
    private $user_address;

    private $model;

    /**
     * OrderController constructor.
     * @param User_address $user_address
     * @param Order $order
     * @param Parent_order $parent_order
     * @param User $user
     * @param Cart $cart
     * @param Trading_stream $trading_stream
     * @param Commodity_info $commodity_info
     */
    function __construct(User_address $user_address, Order $order, Parent_order $parent_order, User $user, Cart $cart, Trading_stream $trading_stream, Commodity_info $commodity_info)
    {
        $this->user_address = $user_address;
        $this->order = $order;
        $this->parent_order = $parent_order;
        $this->user = $user;
        $this->cart = $cart;
        $this->trading_stream = $trading_stream;
        $this->commodity_info = $commodity_info;
//        $this = $user;
    }

    /**
     * 方法 : add_order
     * @User wuqin
     * @DateTime 2018-04-11 13:28
     * @param Request $request
     * @return array|\Illuminate\Http\JsonResponse
     */
    public function add_order(Request $request)
    {
        $post = $request->input();

        if (empty($post) || count($post) == 0) {
            return return_array(1, "非法操作");
        }
        if (empty($post["price"]))
            return return_array(1, "非法价格");

        if (empty($post["address"]))
            return return_array(1, "非法地址");

        $user = get_session_user();
        if (empty($user))
            return return_array(1, "非法用户");
        $this->user = $this->user->find($user["user_id"]);
        if ($this->user->balance < (float)$post["price"])
            return return_message(100, "余额不足,请充值");


        $this->user_address = $this->user_address->find($post["address"]);
        if (empty($this->user_address))
            return return_array(1, "非法地址2");

        //开启事务
        $this->trans_begin();

        //获取该笔订单数据
        $cartData = json_decode(Redis::get("flush_cart" . $user["user_id"]), true, 512);
        if (empty($cartData)) {
            $this->trans_rollback();
            return return_message(1, "订单数据为空");
        }

        //删掉redis key
        $this->user->del_redis("flush_cart" . $user["user_id"]);

        //父订单生成
        $poData = array(
            "user_id" => $user['user_id'],
            "trading_stream_id" => 0,
            "user_address_id" => $this->user_address->user_address_id,
            "all_price" => $post['price'],
        );
        $this->parent_order = $this->parent_order->add_parent_order($poData);
        if (!$this->parent_order->save()) {
            $this->trans_rollback();
            return return_message(1, "父订单生成失败");
        }


        $parent_order = [];
        $parent_info = [
            "price" => 0.00,
//            "ids" => "",
        ];
        //操作开始
        foreach ($cartData as $key => $value) {
            $infoModel = new Commodity_info();
            $infoModel = $infoModel->find($value["commodity_info_id"]);
            if ($infoModel->commodity_info_number < $value["number"]) {
                $mark = $value;
                $this->trans_rollback();
                break;
            }

            //减库存
            $infoModel->commodity_info_number -= $value["number"];
            if (!$infoModel->save()) {
                $this->trans_rollback();
                return return_message(1, $value["commodity_color_name"] . " 丨 " . $value["commodity_size_name"] . " | " . $value["commodity_name"] . " | 库存扣减失败");
            }

            //购物车相应删除
            if (!$this->cart->deleteByPrimary($value["cart_id"])) {
                $this->trans_rollback();
                return return_message(1, $value["commodity_color_name"] . " 丨 " . $value["commodity_size_name"] . " | " . $value["commodity_name"] . " | 购物车删除失败");
            }

            //生成子订单
            $orderModel = new Order();
            $order_data = array(
                "user_id" => $value['user_id'],
                "commodity_id" => $value['commodity_id'],
                "info_id" => $value['info_id'],
                "color_id" => $value['color_id'],
                "size_id" => $value['size_id'],
                "number" => $value['number'],
                "unit_price" => $value['unit_price'],
                "all_price" => $value['all_price'],
                "parent_order_id" => $this->parent_order->parent_order_id,
            );
            $order = $orderModel->add_order($order_data);
            if (!$order) {
                $this->trans_rollback();
                return return_message(1, $value["commodity_color_name"] . " 丨 " . $value["commodity_size_name"] . " | " . $value["commodity_name"] . " | 商品加入订单失败");
            }
            $parent_order[] = $order->toArray();
            $parent_info["price"] += $order->toArray()["all_price"];
//            $parent_info["ids"] .= $order->toArray()["order_id"] . ",";
        }

        //库存不足触发的回滚
        if (isset($mark)) {
            $this->cart->deleteByPrimary($mark["cart_id"]);
            return return_message(1, $mark["commodity_color_name"] . " 丨 " . $mark["commodity_size_name"] . " | " . $mark["commodity_name"] . " | 库存不足");
        }


        if ($this->user->balance < (float)$parent_info["price"]) {
            $this->trans_rollback();
            return return_message(100, "余额不足,请充值1");
        }

        $this->trans_commit();
        return return_message(0, "订单完成", $this->parent_order->toArray());
    }

    /**
     * 方法 : pay_order
     * @User wuqin
     * @DateTime 2018-04-11 13:28
     * @param Request $request
     * @return array|\Illuminate\Http\JsonResponse
     */
    public function pay_order(Request $request)
    {
        $post = $request->input();

        if (empty($post) || count($post) == 0) {
            return return_array(1, "非法操作");
        }
        if (empty($post["price"]))
            return return_array(1, "非法价格");

        if (empty($post["order"]))
            return return_array(1, "订单不得为空");

        $user = get_session_user();
        if (empty($user))
            return return_array(1, "非法用户");
        $this->user = $this->user->find($user["user_id"]);
        if ($this->user->balance < (float)$post["price"])
            return return_message(100, "余额不足,请充值");

        //开启事务
        $this->trans_begin();
        //交易流水
        $type = config('bar.trading_stream.type');
        $tsData = array(
            "user_id" => $user['user_id'],
            "change" => (0 - (float)$post["price"]),
            "info" => $type[1][1],
            "type" => $type[1][0],
        );
        $this->trading_stream = $this->trading_stream->add_trading_stream($tsData);
        if (!$this->trading_stream->save()) {
            $this->trans_rollback();
            return return_message(1, "交易流水生成失败");
        }

        //父订单更新
        $this->parent_order = $this->parent_order->find($post["order"]);
        if (empty($this->parent_order))
            return return_array(1, "订单不存在");
        $this->parent_order->trading_stream_id = $this->trading_stream->trading_stream_id;
        $this->parent_order->state = 1;
        if (!$this->parent_order->save()) {
            $this->trans_rollback();
            return return_message(1, "订单修改失败");
        }

        //扣减用户余额
        $this->user->balance -= (float)$post["price"];
        if (!$this->user->save()) {
            $this->trans_rollback();
            return return_message(1, "用户余额扣减失败");
        }

        $this->trans_commit();
        return return_message(0, "支付成功");
    }

    /**
     * 方法 : cancel_order
     * @User wuqin
     * @DateTime 2018-04-11 13:28
     * @param Request $request
     * @return array
     */
    public function cancel_order(Request $request)
    {
        $post = $request->input();

        if (empty($post) || count($post) == 0) {
            return return_array(1, "非法操作");
        }

        if (empty($post["order"]))
            return return_array(1, "订单不得为空");

        $user = get_session_user();
        if (empty($user))
            return return_array(1, "非法用户");
        $this->user = $this->user->find($user["user_id"]);


    }

    /**
     * 方法 : add_state
     * @User wuqin
     * @DateTime 2018-04-14 13:21
     * @param Request $request
     * @param Parent_order $parent_order
     * @return \Illuminate\Http\JsonResponse
     */
    public function add_state(Request $request, Parent_order $parent_order)
    {
        $post = $request->input();
        if (empty($post))
            return return_message(1, "非法参数");

        if (empty($post["id"]))
            return return_message(1, "非法订单");

        if (empty($post["state"]))
            return return_message(1, "状态码不得为空");

        $parent_order = $parent_order->find($post["id"]);

        if (empty($parent_order) || empty($parent_order->toArray()))
            return return_message(1, "该订单不存在");

        $parent_order->state++;

        if (!$parent_order->save())
            return return_message(1, "更改状态失败");
        return return_message(0, "更改状态成功", $parent_order->toArray());
    }

    /**
     * 方法 : delete_order
     * @User wuqin
     * @DateTime 2018-04-14 13:21
     * @param Request $request
     * @param Parent_order $parent_order
     * @param Order $order
     * @return \Illuminate\Http\JsonResponse
     */
    public function delete_order(Request $request, Parent_order $parent_order, Order $order)
    {
        $post = $request->input();
        if (empty($post))
            return return_message(1, "非法参数");

        if (empty($post["id"]))
            return return_message(1, "非法订单");

        //开启事务
        $this->trans_begin();

        $parent_order = $parent_order->find($post["id"]);

        if (empty($parent_order) || empty($parent_order->toArray())) {
            $this->trans_rollback();
            return return_message(1, "该订单不存在");
        }
        $parent_orderData = $parent_order->toArray();
        if ($parent_orderData["state"] != 6) {
            $this->trans_rollback();
            return return_message(1, "该订单未关闭不可删除");
        }

        $order = $order->getOrderByParent($parent_order->parent_order_id);

        //操作开始
        foreach ($order as $key => $value) {

            $orderModel = new Order();
            $orderModel = $orderModel->deleteByPrimary($value["order_id"]);
            if (!$orderModel) {
                $this->trans_rollback();
                return return_message(1, "子订单删除失败");
            }
        }

        if (!$parent_order->delete()) {
            $this->trans_rollback();
            return return_message(1, "订单删除失败");
        }

        $this->trans_commit();
        return return_message(0, "订单删除成功");
    }

    /**
     * 方法 : close_order
     * @User wuqin
     * @DateTime 2018-04-14 13:21
     * @param Request $request
     * @param Parent_order $parent_order
     * @param Order $order
     * @return \Illuminate\Http\JsonResponse
     */
    public function close_order(Request $request, Parent_order $parent_order, Order $order)
    {
        $post = $request->input();
        if (empty($post))
            return return_message(1, "非法参数");

        if (empty($post["id"]))
            return return_message(1, "非法订单");


        //开启事务
        $this->trans_begin();

        $parent_order = $parent_order->find($post["id"]);

        if (empty($parent_order) || empty($parent_order->toArray())) {
            $this->trans_rollback();
            return return_message(1, "该订单不存在");
        }
        $parent_orderData = $parent_order->toArray();

        $this->user = $this->user->find($parent_orderData["user_id"]);
        if (empty($this->user) || empty($this->user->toArray())) {
            $this->trans_rollback();
            return return_message(1, "该用户不存在");
        }


        $order = $order->getOrderByParent($parent_order->parent_order_id);

        //操作开始
        foreach ($order as $key => $value) {

            $infoModel = new Commodity_info();
            $infoModel = $infoModel->find($value["info_id"]);

            //加库存
            $infoModel->commodity_info_number += $value["number"];
            if (!$infoModel->save()) {
                $this->trans_rollback();
                return return_message(1, "库存返还失败");
            }

        }

        if ($parent_orderData["state"] != 0) {
            //交易流水
            $type = config('bar.trading_stream.type');
            $tsData = array(
                "user_id" => $parent_orderData['user_id'],
                "change" => $parent_orderData["all_price"],
                "info" => $type[2][1],
                "type" => $type[2][0],
            );
            $this->trading_stream = $this->trading_stream->add_trading_stream($tsData);
            if (!$this->trading_stream->save()) {
                $this->trans_rollback();
                return return_message(1, "交易流水生成失败");
            }

            //返还用户余额
            $this->user->balance += (float)$parent_orderData["all_price"];
            if (!$this->user->save()) {
                $this->trans_rollback();
                return return_message(1, "用户余额返还");
            }
        }

        $parent_order->state = 6;

        if (!$parent_order->save()) {
            $this->trans_rollback();
            return return_message(1, "更改状态失败");
        }

        $this->trans_commit();
        return return_message(0, "关闭订单成功");
    }
}
